import asyncio
import websockets
import threading
import cv2
import pyvirtualcam
import time
import re
import colorsys
import numpy as np

HOST = 'localhost'
PORT = 51746
pattern_RunVideo=r'^run\s+(.*)$'
pattern_StopVideo=r'^stop$'
pattern_AgainVideo=''
pattern_ChangeVideo=''

def GetCommandParam(pattern,command):
    match = re.match(pattern, command)
    if match:
        print("命令格式正确")
        # 提取命令参数
        parameters = command.split()[1:]
        print("命令参数:", parameters)
        return parameters
    else:
        print("命令格式不正确")
        return None
class VideoServer:
    def __init__(self):
        self.is_running = False
        self.ws_server = None
        self.ws = None
       
    def start(self):
        self.ws_server = websockets.serve(self.websocket_handler, HOST, PORT)
        print(HOST, PORT,'服务已启动，等待连接...')
        asyncio.get_event_loop().run_until_complete(self.ws_server)
        asyncio.get_event_loop().run_forever()
         

     
    # WebSocket 服务器处理函数
    async def websocket_handler(self,websocket):
        global global_websocket
        global_websocket = websocket

        print(websocket.remote_address,"连接成功！")
        self.ws = websocket
        try:
            while True:
                # 接收客户端发送的消息
                message = await websocket.recv()
                # 在这里处理接收到的消息
                print("收到命令:", message)
                if(message=="start"):
                    self.Start()
                if(message=="stop"):
                    self.Stop()
                
        except websockets.exceptions.ConnectionClosed:
            print(websocket.remote_address,"连接已断开！")
            self.Stop()
      

    def Start(self):
        self.thread = threading.Thread(target=self.camera_loop)
        self.thread.start()
        print("camera_loop已启动！")

    def Stop(self):
        print('停止线程中......')
        self.is_running = False

    def camera_loop(self):
        self.is_running = True
        i=1
        while self.is_running:
            if i%5==0:
                loop = asyncio.new_event_loop()
                loop.run_until_complete(global_websocket.send(str(i)))
                #  global_websocket.send("20")
            print(i)
            i+=1
            time.sleep(1)
        print('线程已停止')
         
 
 
# 启动视频服务
server = VideoServer()
server.start()
